import { ref, onMounted, onUnmounted } from 'vue'

export default function useWebSocket(url: string) {
    const ws = ref<WebSocket | null>(null)
    const isConnected = ref(false)
    const message = ref('')
    const error = ref('')

    const connect = () => {
        ws.value = new WebSocket(url)

        ws.value.onopen = () => {
            isConnected.value = true
        }

        ws.value.onmessage = (event) => {
            message.value = event.data
        }

        ws.value.onerror = (event) => {
            error.value = 'WebSocket error'
            console.error('WebSocket error:', event)
        }

        ws.value.onclose = () => {
            isConnected.value = false
        }
    }

    const send = (data: any) => {
        if (ws.value && isConnected.value) {
            ws.value.send(JSON.stringify(data))
        }
    }

    const close = () => {
        if (ws.value) {
            ws.value.close()
        }
    }

    onMounted(() => {
        connect()
    })

    onUnmounted(() => {
        close()
    })

    return {
        isConnected,
        message,
        error,
        send,
        close,
        connect
    }
} 